﻿using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

namespace ChivalryUnityEditor
{
    /// <summary>
    /// @Author:Teddy
    /// </summary>
	public class SpriteBindWindow : EditorWindow
    {
        [MenuItem("Tools/图片绑定工具")]
        private static EditorWindow CreateWindow()
        {
            return GetWindow<SpriteBindWindow>(false, "图片绑定工具", true);
        }

        private List<SelectionSpriteData> m_selectionDatas;
        private Vector2 m_scroll;

        private void OnEnable()
        {
            Selection.selectionChanged += OnSelectionChanged;
            SpriteBindListener.OnMoveAsset += OnMoveAsset;
            m_selectionDatas = new List<SelectionSpriteData>();
        }

        private void OnDisable()
        {
            Selection.selectionChanged -= OnSelectionChanged;
            SpriteBindListener.OnMoveAsset -= OnMoveAsset;
        }

        private void OnGUI()
        {
            //选中列表
            EditorGUILayout.BeginVertical(GUI.skin.box);
            EditorGUILayout.LabelField(string.Format("选中的图片:({0})", m_selectionDatas.Count));
            m_scroll = EditorGUILayout.BeginScrollView(m_scroll);
            for (int i = 0; i < m_selectionDatas.Count; i++)
            {
                EditorGUILayout.BeginHorizontal();
                SelectionSpriteData data = m_selectionDatas[i];
                GUI.changed = false;
                bool toggle = EditorGUILayout.ToggleLeft("", data.hasBind, GUILayout.MaxWidth(20));
                if (GUI.changed)
                {
                    if (toggle)
                    {
                        BindSprite(GetBindData(), data);
                    }
                    else
                    {
                        UnbindSprite(data);
                    }
                }
                EditorGUILayout.LabelField(data.path);
                EditorGUILayout.EndHorizontal();
            }
            EditorGUILayout.EndScrollView();
            EditorGUILayout.EndVertical();

            //底部工具条
            EditorGUILayout.Space();
            EditorGUILayout.BeginHorizontal();
            if (GUILayout.Button("全部绑定", GUILayout.MaxWidth(100)))
            {
                if (m_selectionDatas.Count == 0)
                    return;

                SpriteBindData bindData = GetBindData();
                for (int i = 0; i < m_selectionDatas.Count; i++)
                {
                    BindSprite(bindData, m_selectionDatas[i]);
                }
            }

            if (GUILayout.Button("全部解绑", GUILayout.MaxWidth(100)))
            {
                if (m_selectionDatas.Count == 0)
                    return;

                for (int i = 0; i < m_selectionDatas.Count; i++)
                {
                    UnbindSprite(m_selectionDatas[i]);
                }
            }
            EditorGUILayout.EndHorizontal();
        }

        /// <summary>
        /// 绑定图片
        /// </summary>
        /// <param name="bindData"></param>
        /// <param name="path"></param>
        private void BindSprite(SpriteBindData bindData, SelectionSpriteData data)
        {
            if (bindData.AddPath(data.path))
            {
                Sprite sprite = AssetDatabase.LoadAssetAtPath<Sprite>(data.path);
                GameObject prefab = new GameObject();
                SpriteRenderer sp = prefab.AddComponent<SpriteRenderer>();
                sp.sprite = sprite;
                string prefabPath = SpriteBindListener.GetBindPath(data.path);
                string folderFullPath = prefabPath.Remove(prefabPath.LastIndexOf('/'));
                new SpriteBindListener.CreateFolderCommand().CreateFolder(folderFullPath, () =>
                {
                    PrefabUtility.CreatePrefab(prefabPath, prefab);
                    DestroyImmediate(prefab);
                    data.hasBind = true;
                });
            }
        }

        /// <summary>
        /// 解绑图片
        /// </summary>
        /// <param name="data"></param>
        private void UnbindSprite(SelectionSpriteData data)
        {
            SpriteBindListener.UnbindSprite(data.path);
            data.hasBind = false;
        }

        /// <summary>
        /// 获取绑定数据
        /// </summary>
        /// <returns></returns>
        private SpriteBindData GetBindData()
        {
            SpriteBindData bindData = Resources.Load<SpriteBindData>("Editor/SpriteBindData");
            if (bindData == null)
            {
                bindData = CreateInstance<SpriteBindData>();
                AssetDatabase.CreateAsset(bindData, "Assets/Resources/Editor/SpriteBindData.asset");
            }
            return bindData;
        }

        private void OnSelectionChanged()
        {
            Object[] selectTextures = Selection.GetFiltered(typeof(Texture), SelectionMode.Assets);
            SpriteBindData bindData = GetBindData();
            m_selectionDatas.Clear();
            for (int i = 0; i < selectTextures.Length; i++)
            {
                string path = AssetDatabase.GetAssetPath(selectTextures[i]);
                SelectionSpriteData data = new SelectionSpriteData()
                {
                    hasBind = bindData.ContainsPath(path),
                    path = path,
                };
                m_selectionDatas.Add(data);
            }
            Repaint();
        }

        private void OnMoveAsset(string path, string newPath)
        {
            for (int i = 0; i < m_selectionDatas.Count; i++)
            {
                if (m_selectionDatas[i].path == path)
                {
                    m_selectionDatas[i].path = newPath;
                    Repaint();
                    break;
                }
            }
        }

        private class SelectionSpriteData
        {
            public bool hasBind;
            public string path;
        }
    }
}